<template>
  <div>
    <el-row>
      <el-col :span="24">
        <div class="search-box">
          <el-form :inline="true" size="medium">
            <el-form-item>
              <el-button type="primary" @click="showAddDialogForm">新增</el-button>
            </el-form-item>
          </el-form>

          <el-form :inline="true" size="medium" :model="searchForm">
            <el-form-item>
              <el-button type="primary" @click="search">刷新</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>

    <el-table
      :data="tableData"
      :header-cell-style="{backgroundColor:'#f4f4f5',textAlign:'center'}"
      :cell-style="{textAlign:'center'}"
      :height="tableHeight"
      border
      style="width: 100%">
      <el-table-column
        prop="serialNumber"
        label="编号"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="name"
        label="考勤组名称"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="workPeople"
        label="考勤人员"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="workResponsible"
        label="考勤组负责人"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="workClasses"
        label="班次"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="workTime"
        label="考勤时间"
        min-width="120">
      </el-table-column>
      <!-- <el-table-column
        prop=""
        label="打卡方式"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop=""
        label="加班规则"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop=""
        label="外勤规则"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop=""
        label="休息日打卡规则"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop=""
        label="补卡规则"
        min-width="120">
      </el-table-column> -->

      <el-table-column
        prop="address"
        label="操作"
        min-width="250">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
       <span class="demonstration"></span>
       <el-pagination
         @size-change="handleSizeChange"
         @current-change="handleCurrentChange"
         :current-page="currentPage"
         :page-sizes="[10, 20, 50, 100,200]"
         :page-size="pageSize"
         layout="total, sizes, prev, pager, next, jumper"
         :total="total">
       </el-pagination>
     </div>

    <el-dialog :title="editForm.id==0?'新增':'修改'" :visible.sync="editFormVisible" width="500px" :close-on-click-modal="false">
      <el-form :model="editForm" ref="editForm" :rules="editRules">
        <el-form-item label="编号" label-width="120px" prop="serialNumber">
          <el-input v-model="editForm.serialNumber" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="考勤组名称" label-width="120px" prop="name">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="考勤人员" label-width="120px" prop="workPeople">
          <el-select v-model="editForm.workPeople"   multiple placeholder="请选择" style="width: 100%;"
          >
              <el-option
                v-for="item in UserList"
                :key="item.id"
                :label="item.name"
                :value="item.name">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="考勤组负责人" label-width="120px" prop="workResponsible">
          <el-select v-model="editForm.workResponsible"   placeholder="请选择" style="width: 100%;"
          >
              <el-option
                v-for="item in TestUserList"
                :key="item.id"
                :label="item.nickname"
                :value="item.nickname">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="考勤班次" label-width="120px" prop="workClasses">
          <el-select v-model="editForm.workClasses"   placeholder="请选择" style="width: 100%;"
          >
              <el-option
                v-for="item in goClassesList"
                :key="item.id"
                :label="item.name+'('+dateFormatter(item.beOnDutyTime)+'-'+dateFormatter(item.offDutyTime)+')'"
                :value="item.name"
                >

              </el-option>
            </el-select>
        </el-form-item>
        <el-col :span="24">
          <el-form-item label="考勤时间" label-width="120px" prop="workTime">
            <el-button size="mini" type="primary" @click="handleTaskDone(editForm.workClasses)">设置</el-button>

          </el-form-item>
        </el-col>
        <!-- <el-form-item label="打卡方式" label-width="120px" prop="name">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="加班规则" label-width="120px" prop="name">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="外勤规则" label-width="120px" prop="name">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="休息日打卡规则" label-width="120px" prop="name">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="补卡规则" label-width="120px" prop="name">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item> -->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click.native.prevent="submitForm" :loading="loading">{{ editForm.id==0?'添 加':'修 改' }}</el-button>
      </div>
    </el-dialog>

    <el-dialog title="考勤时间" :visible.sync="doneFormVisible" width="700px" :close-on-click-modal="false">

        <el-row>
          <el-col :span="24">
            <table class="test-item-table">
              <tr>

                <th>工作日</th>
                <th>班次时间段</th>
                <th>操作</th>


              </tr>

              <tr v-for="(item,index) in workDay">

                <td>{{item.name}}</td>
                <td>{{item.time}}</td>
                <td>
                  <input v-model="doneForm.doneTaskItemIds" type="checkbox" :value="item.name" /></td>


              </tr>

            </table>
          </el-col>
        </el-row>

      <div slot="footer" class="dialog-footer" style="margin-top: 20px;">
        <el-button @click="doneFormVisible = false">取 消</el-button>
        <template >
        <el-button type="primary" @click.native.prevent="submitDoneSave">确定</el-button>

        </template>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {validPhone} from '@/common/utils/validate.js'
import request from '@/common/utils/request.js'
import util from '@/common/utils/util.js'
import {getGoCheckPnWorkAttendanceList, addGoCheckPnWorkAttendance, updateGoCheckPnWorkAttendance, deleteGoCheckPnWorkAttendance} from "@/api/go_check_on_work_attendance";
import {getTestUserList} from "../../../api/test_workload.js";
import {getGoPersonnelList} from "../../../api/go_personnel.js"
import {getGoClassesList} from "@/api/go_classes.js";
export default {
  name: "goCheckOnWorkAttendance",
  data() {
    return {
      total: 0,
      pageSize: 10,
      currentPage: 1,
      tableData: [],
      tableHeight: 200,
      editFormVisible:false,
      doneFormVisible:false,
      loading: false,
      TestUserList:[],
      UserList:[],
      goClassesList:[],
      workDay:[],
      doneForm:{
        doneTaskItemIds:[],

      },
      editForm: {
        id: 0,
        name: '',
        serialNumber: '',
        workPeople: '',
        workResponsible: '',
        workClasses: '',

        workTime:{

        },
      },
      editRules: {
        serialNumber: [{ required: true, message:"请输入编号", trigger: 'blur'}],
        name: [{ required: true, message:"请输入名称", trigger: 'blur'}],
      },
      loadingDiv: null,
      searchForm: {

      },
      roleList:[],
    }
  },
  watch:{

  },
  mounted() {
    this.getDataList(this.currentPage);

    this.$nextTick(() => {
        this.tableHeight = document.documentElement.clientHeight - 198;
    })
    window.onresize = () => {
      this.$nextTick(() => {
          this.tableHeight = document.documentElement.clientHeight - 198;
      })
    }
  },
  methods: {

    showAddDialogForm() {
      if(this.$refs.editForm){
        this.$refs.editForm.clearValidate();
      }
      this.editForm.id = 0
      this.editForm.name = "";
      this.editForm.serialNumber = "";
      this.editForm.workPeople = [];
      this.editForm.workResponsible = "";
      this.editForm.workClasses = "";
      this.editForm.workTime = [];
      this.doneForm.doneTaskItemIds = [];
      this.editForm.note = "";
      this.editFormVisible = true;
    },
    handleEdit(index, row) {

      if(this.$refs.editForm){
        this.$refs.editForm.clearValidate();
      }
      this.editForm.id = row.id;
      this.editForm.name = row.name;
      this.editForm.serialNumber = row.serialNumber;
      this.editForm.workPeople = row.workPeople.split(",");
      this.editForm.workResponsible = row.workResponsible;
      this.editForm.workClasses = row.workClasses;
      let arrStr = row.workTime.split(",")
      this.doneForm.doneTaskItemIds = arrStr;
      this.editForm.workTime = arrStr;
      this.editFormVisible = true;

    },

    format(time, format) {
                    var t = new Date(time);
                    var tf = function (i) { return (i < 10 ? '0' : '') + i };
                    return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
                        switch (a) {
                            case 'yyyy':
                                return tf(t.getFullYear());
                                break;
                            case 'MM':
                                return tf(t.getMonth() + 1);
                                break;
                            case 'mm':
                                return tf(t.getMinutes());
                                break;
                            case 'dd':
                                return tf(t.getDate());
                                break;
                            case 'HH':
                                return tf(t.getHours());
                                break;
                            case 'ss':
                                return tf(t.getSeconds());
                                break;
                        }
                    })
                },
      dateFormatter(row, column) {
      			var t = new Date(row);
      				return this.format(t,'HH:mm:ss');


      		},
    submitForm() {
      this.$refs.editForm.validate(valid => {
        if(valid) {
          this.loading = true;
          let loadingText = "添加中...";
          if(this.editForm.id){
            loadingText = "修改中...";
          }
          const loadingDiv = util.showLoading(loadingText)
          let func = updateGoCheckPnWorkAttendance
          if(this.editForm.id == 0){
            func = addGoCheckPnWorkAttendance
          }
          func(this.editForm).then(res => {
            let title = "修改"
            if(this.editForm.id == 0){
              title = "添加"
            }
            if(res.code == 0) {
              this.$alert(res.msg, title+"失败", {dangerouslyUseHTMLString:true,type:'warning'})
            }else if(res.code == 1) {
              this.$alert(res.msg, title+"成功", {dangerouslyUseHTMLString:true,type:'success'})
                .then(()=> {
                  this.editFormVisible=false;
                  this.getDataList(this.currentPage)
                })
            }
            this.loading = false;
            loadingDiv.close();
          }).catch(res => {
            this.loading = false;
            loadingDiv.close();
          })
        }
      });
    },
    handleDelete(index, row) {
      let loadingDiv;
      this.$confirm("是否确认删除："+row.name+"?","删除确认").then(res=>{
        if(res='confirm'){
          loadingDiv = util.showLoading("删除中...")
          return deleteGoCheckPnWorkAttendance({id: row.id})
        }
      }).then(res => {
        loadingDiv.close();
        if(res.code == 0) {
          this.$alert(res.msg, "删除失败", {dangerouslyUseHTMLString:true,type:'warning'})
        }else if(res.code == 1) {
          this.$alert(res.msg, "删除成功", {dangerouslyUseHTMLString:true,type:'success'})
            .then(res=>{
              this.editFormVisible=false;
              this.getDataList(this.currentPage)
            })
        }
      }).catch(res=>{
        if (loadingDiv){
          loadingDiv.close();
        }
      })
    },
    submitDoneSave(){
      this.editForm.workTime = this.doneForm.doneTaskItemIds;
      this.doneFormVisible = false;
    },


    handleTaskDone(name){
      if(util.isEmpty(name)){
        this.$message.error('请选择考勤班次');
        return;
      }
      let time = '';
      let times = '';
      for(var i=0;i<this.goClassesList.length;i++){
        if(this.goClassesList[i].name == name){
          time = this.goClassesList[i].beOnDutyTime;
          times = this.goClassesList[i].offDutyTime
        }
      }

      time = this.dateFormatter(time);
      times = this.dateFormatter(times);
      this.workDay = [],
      this.workDay.push({
          "name": '星期一',
          "time": time +'-'+times
          });
      this.workDay.push({
          "name": '星期二',
          "time": time +'-'+times
          });
      this.workDay.push({
          "name": '星期三',
          "time": time +'-'+times
          });
      this.workDay.push({
          "name": '星期四',
          "time": time +'-'+times
          });
      this.workDay.push({
          "name": '星期五',
          "time": time +'-'+times
          });
      this.workDay.push({
          "name": '星期六',
          "time": time +'-'+times
          });
      this.workDay.push({
          "name": '星期日',
          "time": time +'-'+times
          });

      this.doneFormVisible=true;

    },

    getDataList(pageNum){
      const loadingDiv = util.showLoading()

      getGoCheckPnWorkAttendanceList({
        pageSize: this.pageSize,
        pageNum: pageNum,
      }).then(res => {
        if(res.code == 0) {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
        }else if(res.code == 1) {
          let data = res.data;
          this.currentPage = pageNum;
          this.total = data.total;
          this.tableData = data.dataList;
        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      })
      getTestUserList().then(res => {
        if(res.code == 0) {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
        }else if(res.code == 1) {
           this.TestUserList = res.data;
        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      })
      getGoPersonnelList({
        pageSize: this.pageSize,
        pageNum: pageNum,
      }).then(res => {
        if(res.code == 0) {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
        }else if(res.code == 1) {
          let data = res.data;
          this.UserList = data.dataList;
        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      })

      getGoClassesList({
        pageSize: this.pageSize,
        pageNum: pageNum,
      }).then(res => {
        if(res.code == 0) {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
        }else if(res.code == 1) {
          let data = res.data;
          this.goClassesList = data.dataList;
        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      })
    },
    search() {
      this.getDataList(this.currentPage)
    },
    handleSizeChange(pageSize) {
            this.pageSize = pageSize;
            this.getDataList(1)
          },
    handleCurrentChange(pageNum) {
            this.getDataList(pageNum);
          },
  }
}
</script>

<style scoped lang="scss">
  // @import "~@/common/styles/element-variables.scss";
  .search-box {
    background-color: #FFFFFF;
    min-height: 36px;
    line-height: 36px;
    padding-top: 2px;
    padding-bottom: 6px;
    .el-form-item {
      margin-bottom: 0px !important;
    }
    .el-form--inline {
      display: inline-block;
    }
  }
  .pagination-box {
    text-align: left;
    margin-top: 10px;
  }
  .test-item-table{
    width: 100%;
    border-collapse: collapse;
    tr{
      height: 40px;
    }

    th, td {
      width: 4%;
      text-align: center;
      border: 1px solid #CCC;
    }
    th {
      background-color: #EDF2FC;
    }
  }
</style>
<style lang="scss">
  .el-dialog__header {

  }
  .el-dialog__body {
    padding-top: 10px;
    padding-bottom: 0px;
  }
  .el-dialog__footer {
    padding-top: 0px;
  }
</style>
